from flask import Blueprint

from controllers import R
from mauth import HasPerm
from models.schema_field import SchemaField
from services.schema_field_service import SchemaFieldService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.schema_field_validator import SchemaFieldForm

# 声明一个蓝图
schema_field = Blueprint("schema_field", __name__, url_prefix="/dev/schemaField")

# 声明一个模型字段业务服务
schema_field_service = SchemaFieldService(model=SchemaField)


@schema_field.route("/detail", methods=["POST"])
@HasPerm(access="dev:schemaField:detail", name="通过id获取模型字段信息")
def schema_field_detail():
    """
    通过id获取模型字段信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = SchemaField.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = schema_field_service.detail(form)
    if u is not None:
        return R.data(u)
    else:
        return R.fail("该记录不存在")


@schema_field.route("/page", methods=["POST"])
@HasPerm(access="dev:schemaField:page", name="分页查询模型字段列表")
def schema_field_page():
    """
    分页查询模型字段列表
    :return:
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(schema_field_service.page(form))


@schema_field.route("/save", methods=["POST"])
@HasPerm(access="dev:schemaField:save", name="添加模型字段")
def schema_field_save():
    """
    添加模型字段
    :return:
    """
    form = SchemaFieldForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_field_service.save(form)
    return R.success("添加模型字段成功")


@schema_field.route("/update", methods=["POST"])
@HasPerm(access="dev:schemaField:update", name="修改模型字段")
def schema_field_update():
    """
    修改模型字段
    :return:
    """
    form = SchemaFieldForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_field_service.update(form)
    return R.success("修改模型字段成功")


@schema_field.route("/remove", methods=["POST"])
@HasPerm(access="dev:schemaField:remove", name="删除模型字段")
def schema_field_remove():
    """
    删除模型字段
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_field_service.remove(form)
    return R.success("删除模型字段成功")
